package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.bean.dto.SysRolePermissionDto;
import cn.com.cifi.mars.bean.vo.sys.req.SaveSysRolePermissionReqParam;
import cn.com.cifi.mars.bean.vo.sys.rsp.RolePermissionVo;
import cn.com.cifi.mars.constant.IsDisableEnum;
import cn.com.cifi.mars.entity.common.SysRoleOrgDataPermission;
import cn.com.cifi.mars.entity.common.SysRolePermission;
import cn.com.cifi.mars.mapper.mars.SysRolePermissionMapper;
import cn.com.cifi.mars.service.SysRolePermissionService;
import cn.com.cifi.mars.util.UUIDUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 角色权限关联表 服务实现类
 * </p>
 *
 * @author yyd
 * @since 2019-09-20
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService {

	@Autowired
	private SysRolePermissionMapper sysRolePermissionMapper;

	/**
	 * 添加角色功能权限
	 */
	@Transactional
	@Override
	public int addSysRolePermission(SaveSysRolePermissionReqParam param, String name) {
		//先删除角色关联数据
		sysRolePermissionMapper.deleteRoleId(param.getRoleId());
		// 添加关联关系
		int num = 0;
		for (String permissionId : param.getPerIds()) {
			SysRolePermission bean = new SysRolePermission();
			bean.setPermissionId(permissionId);
			bean.setRoleId(param.getRoleId());
			bean.setCreateby(name);
			bean.setCreateTime(LocalDateTime.now());
			bean.setId(UUIDUtils.create());
			num = sysRolePermissionMapper.insert(bean);
		}
		return num;
	}

	/**
	 * 显示角色功能权限树
	 */
	@Override
	public RolePermissionVo querySysRolePermissionTree(String roleId) {
		RolePermissionVo vo=new RolePermissionVo();
		List<SysRolePermissionDto> list=sysRolePermissionMapper.selectRolePermissionTree(roleId,IsDisableEnum.NO.getKey()+"");
		//List<SysRolePermissionDto> listTree=buildTree(list,"");
		//JSONArray trssJson= JSONArray.parseArray(JSON.toJSONString(listTree));
		vo.setList(list);
		return vo;
	}
	
	/**
	 * 递归子节点
	 * @param list
	 * @param parentId
	 * @return
	 */
	public static List<SysRolePermissionDto> buildTree(List<SysRolePermissionDto> list,String parentId){
		List<SysRolePermissionDto> menus=new ArrayList<>();
	    for (SysRolePermissionDto menu : list) {  
	    	  //本身id
	          String menuId = menu.getPerCode();
	          //父id
	          String pid = menu.getParentCode();
	          if (parentId.equals(pid)) {  
	              List<SysRolePermissionDto> menuLists = buildTree(list, menuId);  
	              menu.setChildMenu(menuLists);
	              menus.add(menu);  
	          }  
	    }  
		return menus;
	}
}
